<template>
    <view>
        <view class="top-box">
            <view class="logo" v-if="weixin == 2" style="display: inline-block; position: absolute; left: 20rpx" @tap="goBack"><van-icon name="arrow-left" size="22" /></view>
            <text>{{ otherName ? otherName : newslist[0].name }}</text>
        </view>

        <view class="news" :id="'item' + (index + 1)" @tap="outbtn" style="height: 100%; top: 160rpx; position: relative; max-height: 1352rpx; overflow-y: scroll">
            <!-- <view class="chat-notice" wx:if="{{userInfo}}">系统消息: 欢迎 {{ userInfo.nickName }} 加入聊天室</view> -->

            <scroll-view
                @scrolltoupper="onPullDownRefresh"
                :scroll-y="true"
                class="history"
                :style="'height:' + outHeight + ';padding: 0 20rpx;width: 95%;'"
                :scroll-top="scrollTop"
                :scroll-into-view="scrollLast"
            >
                <block v-for="(item, index) in newslist" :key="index">
                    <!-- 时间 -->

                    <view class="time">{{ item.createTime }}</view>

                    <!-- 单个消息1 客服发出（左） -->

                    <view v-if="item.senderIdentityId != identityId" :id="'msg-' + index" style="display: flex; padding-bottom: 20rpx">
                        <image
                            style="min-width: 100rpx; min-height: 100rpx; width: 100rpx; border-radius: 100rpx; margin-right: 10rpx; height: 100rpx" 
                            :src="item.headImageUrl ? item.headImageUrl : '/assets/img/user/tx.png'" mode="widthFix"
                        ></image>
                        <!-- <view style='width: 4vw; height: 11vw; margin-left: 0.5vw; display: flex; align-items: center; z-index: 9;'>
    <image style='width: 4vw;' src='/assets/img/system.png' mode='widthFix'></image>
  </view> -->
                        <view class="leftMsg" v-if="item.content">{{ item.content }}</view>
                        <view class="leftMsg" v-if="item.enclosure">
                            <image @tap="imgYu" :data-src="item.enclosure" style="width: 200rpx; margin-right: 10rpx" :src="item.enclosure" mode="widthFix"></image>
                        </view>
                    </view>

                    <!-- 单个消息2 用户发出（右） -->

                    <view v-else :id="'msg-' + index" style="display: flex; justify-content: flex-end; padding-bottom: 20rpx">
                        <view class="rightMsg" v-if="item.content">{{ item.content }}</view>
                        <view class="rightMsg" v-if="item.enclosure">
                            <image @tap="imgYu" :data-src="item.enclosure" style="width: 200rpx; margin-right: 10rpx" :src="item.enclosure" mode="widthFix"></image>
                        </view>
                        <!-- <view style='width: 4vw; height: 11vw; margin-right: 0.5vw; display: flex; align-items: center; z-index: 9;'>
    <image style='width: 4vw;' src='/assets/img/system.png' mode='widthFix'></image>
  </view> -->
                        <image
                            style="min-width: 100rpx; min-height: 100rpx; width: 100rpx; border-radius: 100rpx; margin-left: 10rpx; height: 100rpx" mode="widthFix"
                            :src="item.headImageUrl ? item.headImageUrl : '../../static/assets/img/user/tx.png'"
                        ></image>
                    </view>
                </block>
            </scroll-view>
        </view>

        <view id="flag"></view>
        <!-- 聊天输入 -->
        <view class="message">
            <form @reset="cleanInput" class="sendMessage">
                <!-- <input type="text" placeholder="请输入聊天内容.." value="{{massage}}" bindinput='bindChange'></input> -->
                <input @confirm="sendClick" placeholder="发消息…" :adjust-position="false" :value="massage" confirm-type="send" @focus="focus" @blur="blur" />
                <image @tap="increaseFun" src="../../static/assets/img/add1.png" style="width: 44rpx; margin: 20rpx; height: 44rpx" mode="widthFix"></image>
                <!-- <button type="primary" bindtap='send' formType="reset" size="small" button-hover="blue">发送</button> -->
            </form>
            <view :class="'increased ' + (aniStyle ? 'slideup' : 'slidedown')" v-if="increase">
                <view @tap="chooseImage">
                    <image class="image" src="../../static/assets/img/photo.png" mode="widthFix"></image>
                    <view style="text-align: center; width: 112rpx">相册</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
// pages/socks/socks.js
const app = getApp();
import util from './../../utils/util.js';
import api from './../../utils/api.js';
import websocket from './../../utils/websocket.js';
let stompClient = '';
export default {
    data() {
        return {
            pageNumber: 1,
            outHeight: '100%',
            outHeightBottom: '0rpx',
            scrollLast: null,

            newslist: [
                // {
                //   avatarUrl: "",
                //   nickName: "2",
                //   type: "text",
                //   content: "2222"
                // },
            ],

            userInfo: {},
            scrollTop: 0,
            increase: false,
			weixin:uni.getStorageSync('weixin'),
            //图片添加区域隐藏
            aniStyle: true,

            //动画效果
            message: '',

            previewImgList: [],
            inputBottom: '',
            name: '',
            identityId: '',
            id: '',
            manageId: '',
            otherName: '',
            recipientUserId: '',
            reserveRecordId: '',
            massage: '',
			index:0
        };
    },
    onLoad: function (options) {
		console.log(options)
        let res = uni.getSystemInfoSync();

        if (res.platform == 'ios') {
            this.setData({
                inputBottom: '700rpx'
            });
        } else {
            this.setData({
                inputBottom: '580rpx'
            });
        } //安卓

        const identityId = uni.getStorageSync('identityId');
        const name = uni.getStorageSync('name');
        this.setData({
            name: name,
            identityId: identityId
        });

        if (options.id) {
            this.setData({
                id: options.id
            });
        }

        if (options.manageId) {
            this.setData({
                manageId: options.manageId
            });
        }

        if (options.otherName) {
            this.setData({
                otherName: options.otherName
            });
        }

        if (options.recipientUserId) {
            this.setData({
                recipientUserId: options.recipientUserId
            });
        }
        if (options.reserveRecordId) {
            this.setData({
                reserveRecordId: options.reserveRecordId
            });
        }

        var that = this; //socket链接

        websocket.connect('?token=' + uni.getStorageSync('AUTHORIZATION'), function (res) {
            that.getData();
        }); //调通接口

        this.getData();
    },
    onShow() {
        var that = this;
        websocket.connect('?token=' + uni.getStorageSync('AUTHORIZATION'), function (res) {
            that.getData();
        });
        that.getData();
    },
    onHide() {
        uni.closeSocket();
    },
    onUnload() {
        uni.closeSocket();
    },
    //监听用户下拉动作
    onPullDownRefresh(e) {
        let num = this.pageNumber + 1;
        this.setData(
            {
                pageNumber: num
            },
            () => this.getData(1)
        );
    },
    onReachBottom(e) {
        console.log('上拉刷新');
    },
    methods: {
        getScollBottom() {
            this.setData({
                scrollLast: 'msg-' + (this.newslist.length - 1)
            });
        },

        blur() {
            this.setData({
                outHeight: '100%',
                outHeightBottom: '0rpx'
            });
            this.getScollBottom();
        },

        focus() {
            this.setData({
                outHeight: '50%',
                outHeightBottom: this.inputBottom
            });
            this.getScollBottom();
        },

        goBack() {
            uni.navigateBack({
                delta: 1
            });
        },

        /**
         * 生命周期函数--监听页面加载
         */
        getData(needBottom) {
            var that = this;
            util.request(
                api.getMessageList +
                    '?pageNumber=1&pageSize=' +
                    this.pageNumber * 10 +
                    '&unionId=' +
                    uni.getStorageSync('unionId') +
                    '&manageId=' +
                    (this.manageId ? this.manageId : '') +
                    '&id=' +
                    (this.id ? this.id : ''),
                '',
                'get'
            ).then((res) => {
                for (var i = 0; i < res.data.content.length; i++) {
                    if (res.data.content[i].senderIdentityId != uni.getStorageSync('identityId')) {
                        res.data.content[i].name = res.data.content[i].senderNickname;
                    }

                    if (res.data.content[i].recipientUserId != uni.getStorageSync('identityId')) {
                        res.data.content[i].name = res.data.content[i].recipientNickname;
                    }
                }

                that.setData({
                    newslist: res.data.content.reverse() // message: res.data.message
                });
                for (var i = 0; i < that.newslist.length; i++) {
                    if (!that.recipientUserId && that.newslist[i].senderIdentityId != that.identityId) {
                        this.setData({
                            recipientUserId: that.newslist[i].senderIdentityId
                        });
                    }

                    if (!that.recipientUserId && that.newslist[i].recipientUserId != that.identityId) {
                        this.setData({
                            recipientUserId: that.newslist[i].recipientUserId
                        });
                    } // if (that.data.newslist[i].enclosure) {
                    //   (function (i,img){
                    //     util.request(api.getEncryPath + "?path=" + img, "", "POST")
                    //     .then(res => {
                    //       console.log(res)
                    //       that.data.newslist[i].enclosure = res;
                    //       that.setData({
                    //         newslist: that.data.newslist
                    //       })
                    //     })
                    //     })(i,that.data.newslist[i].enclosure);
                    // }
                    // if (that.data.newslist[i].headImageUrl) {
                    //   (function (i,img){
                    //     util.request(api.getEncryPath + "?path=" + img, "", "POST")
                    //     .then(res => {
                    //       console.log(res)
                    //       that.data.newslist[i].headImageUrl = res;
                    //       that.setData({
                    //         newslist: that.data.newslist
                    //       })
                    //     })
                    //     })(i,that.data.newslist[i].headImageUrl);
                    // }

                    if (!needBottom) {
                        that.getScollBottom();
                    }
                }
            });
        },

        //事件处理函数
        send: function () {
            var that = this;

            if (this.message.trim() == '') {
                uni.showToast({
                    title: '消息不能为空哦~',
                    icon: 'none',
                    duration: 2000
                });
            } else {
                setTimeout(function () {
                    that.setData({
                        increase: false
                    });
                }, 500);
                websocket.send(
                    '{ "content": "' +
                        this.message +
                        '", "date": "' +
                        utils.formatTime(new Date()) +
                        '","type":"text", "nickName": "' +
                        this.userInfo.nickName +
                        '", "avatarUrl": "' +
                        this.userInfo.avatarUrl +
                        '" }'
                );
                this.bottom();
            }
        },

        /**
         * 发送点击监听
         */
        sendClick: function (e) {
            var that = this;
            console.log(e.detail.value);

            if (!e.detail.value || !that.manageId) {
                return;
            }

            var param = {
                unionId: uni.getStorageSync('unionId'),
                content: e.detail.value,
                // enclosureType: 1, //附件类型，1图片，2视频，附件上传时必传
                // reserveRecordId: that.data.reserveRecordId?that.data.reserveRecordId:"",
                manageId: that.manageId ? that.manageId : '',
                recipientUserId: that.recipientUserId,
                id: this.id ? this.id : '' // enclosure:res
            };
            util.request(api.uploadUserChatMessage, param, 'POST').then((res) => {
                console.log(res);
                that.setData({
                    massage: ''
                });
                that.setData({
                    increase: false,
                    aniStyle: false
                });
                that.getData();
            }); // this.setData({
            //   message: res.detail.value
            //  })
        },

        //监听input值的改变
        bindChange(res) {
            this.setData({
                message: res.detail.value
            });
        },

        cleanInput() {
            //button会自动清空，所以不能再次清空而是应该给他设置目前的input值
            this.setData({
                message: this.message
            });
        },

        increaseFun() {
            this.setData({
                increase: true,
                aniStyle: true
            });
        },

        //点击空白隐藏message下选框
        outbtn() {
            this.setData({
                increase: false,
                aniStyle: true
            });
        },

        imgYu: function (event) {
            var src = event.currentTarget.dataset.src; //获取data-src

            var imgList = [src]; //获取data-list
            //图片预览

            uni.previewImage({
                current: src,
                // 当前显示图片的http链接
                urls: imgList // 需要预览的图片http链接列表
            });
        },

        //发送图片
        chooseImage() {
            var that = this;
            uni.chooseImage({
                count: 1,
                // 默认9
                sizeType: ['original', 'compressed'],
                // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'],
                // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                    var tempFilePaths = res.tempFilePaths;
                    uni.uploadFile({
                        url: api.vueUpload,
                        // 仅为示例，非真实的接口地址
                        filePath: tempFilePaths[0],
                        name: 'file',
                        formData: {
                            user: 'test'
                        },
                        header: {
                            Authorization: uni.getStorageSync('AUTHORIZATION') //如果需要token的话要传
                        },

                        success(res) {
                            var data = JSON.parse(res.data);
                            var param = {
                                unionId: uni.getStorageSync('unionId'),
                                enclosureType: 1,
                                //附件类型，1图片，2视频，附件上传时必传
                                // reserveRecordId: that.data.reserveRecordId?that.data.reserveRecordId:"",
                                manageId: that.manageId ? that.manageId : '',
                                recipientUserId: that.recipientUserId,
                                enclosure: data.data,
                                id: this.id ? this.id : ''
                            };
                            util.request(api.uploadUserChatMessage, param, 'POST').then((res) => {
                                console.log(res);
                                that.getData();
                                that.setData({
                                    increase: false,
                                    aniStyle: false
                                });
                            }); // if (data.data) {
                            //   util.request(api.getEncryPath + "?path=" + data.data, "", "POST")
                            //     .then(res => {
                            //       console.log(res)
                            //       var param = {
                            //         unionId: wx.getStorageSync("unionId"),
                            //         enclosureType: 1, //附件类型，1图片，2视频，附件上传时必传
                            //         reserveRecordId: that.data.reserveRecordId,
                            //         enclosure:res
                            //       }
                            //       util
                            //         .request(
                            //           api.uploadUserChatMessage,
                            //           param,
                            //           "POST"
                            //         ).then(
                            //           res => {
                            //             console.log(res)
                            //             that.getData();
                            //           }
                            //         );
                            //     });
                            // }
                        }
                    }); // wx.uploadFile({
                    //   url: 'wss://www.xxx.cn', //服务器地址
                    //   filePath: tempFilePaths[0],
                    //   name: 'file',
                    //   headers: {
                    //     'Content-Type': 'form-data'
                    //   },
                    //   success: function (res) {
                    //     if (res.data) {
                    //       that.setData({
                    //         increase: false
                    //       })
                    //       websocket.send('{"images":"' + res.data + '","date":"' + utils.formatTime(new Date()) + '","type":"image","nickName":"' + that.data.userInfo.nickName + '","avatarUrl":"' + that.data.userInfo.avatarUrl + '"}')
                    //       that.bottom()
                    //     }
                    //   }
                    // })
                }
            });
        },

        //图片预览
        previewImg(e) {
            var that = this; //必须给对应的wxml的image标签设置data-set=“图片路径”，否则接收不到

            var res = e.target.dataset.src;
            var list = this.previewImgList; //页面的图片集合数组
            //判断res在数组中是否存在，不存在则push到数组中, -1表示res不存在

            if (list.indexOf(res) == -1) {
                this.previewImgList.push(res);
            }

            uni.previewImage({
                current: res,
                // 当前显示图片的http链接
                urls: that.previewImgList // 需要预览的图片http链接列表
            });
        },

        //聊天消息始终显示最底端
        bottom: function () {
            var query = uni.createSelectorQuery();
            query.select('#flag').boundingClientRect();
            query.selectViewport().scrollOffset();
            query.exec(function (res) {
                uni.pageScrollTo({
                    scrollTop: res[0].bottom // #the-id节点的下边界坐标
                });
                res[1].scrollTop; // 显示区域的竖直滚动位置
            });
        },

        onPullDownRefresh() {
            console.log('占位：函数 onPullDownRefresh 未声明');
        }
    }
};
</script>
<style>
@import './socks.css';
</style>
